﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlexFlow.Common.Collections;
using System.Web;
using FlexFlow.Model;
using FlexFlow.Base.Interface;

namespace FlexFlow.Runtime
{
    /// <summary>
    /// 表示基于内存的在线用户池，用来管理在线的用户
    /// </summary>
    public class InProcOnlineUserPool : AutoClearnCollection<OnlineUserInfoHolder>, IOnlineUserPool
    {
        /// <summary>
        /// 表示已登录的用户的信息ID在客户端存储所用的标识
        /// </summary>
        public static string LoginedUserIdentityKey { get; private set; }
        /// <summary>
        /// 从指定HttpRequest取得已登录的用户信息
        /// </summary>
        /// <param name="req">
        /// 用来获取信息的HttpRequest
        /// </param>
        /// <returns>
        /// 取得的用户信息，如果用户未登录或不存在，则返回null
        /// </returns>
        public LoginedUserInfo GetLoginedUserInfo(HttpRequestBase req)
        {
            HttpCookie cookie = req.Cookies[LoginedUserIdentityKey];
            if (cookie == null)
            {
                return null;
            }
            string uidString = req.Cookies[LoginedUserIdentityKey].Value;
            Guid uid;
            if (Guid.TryParse(uidString, out uid))
            {
                return GetLoginedUserInfo(uid);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 根据指定的登录用户ID取得登录用户信息实例
        /// </summary>
        /// <param name="identity">
        /// 已登录的用户的登录信息ID
        /// </param>
        /// <returns>
        /// 取得的用户信息，如果用户信息不存在，则返回null
        /// </returns>
        public LoginedUserInfo GetLoginedUserInfo(Guid identity)
        {
            OnlineUserInfoHolder infoHolder = this.FirstOrDefault(m => m.LoginedUser.Identity == identity);
            if (infoHolder == null)
            {
                return null;
            }
            else
            {
                infoHolder.LastOperateTime = DateTime.Now;
                return infoHolder.LoginedUser;
            }
        }
        /// <summary>
        /// 通过userId取得已登录用户的信息
        /// </summary>
        /// <param name="userId">
        /// 用户Id
        /// </param>
        /// <returns>
        /// 取得的用户信息，如果用户未登录，则返回null
        /// </returns>
        public LoginedUserInfo GetLoginedUserInfoByUid(Guid userId)
        {
            var logInfo = this.FirstOrDefault(m => m.LoginedUser.UserId == userId);
            if (logInfo == null)
            {
                return null;
            }
            return logInfo.LoginedUser;
        }
        /// <summary>
        /// 初始化在线用户池的静态变量
        /// </summary>
        static InProcOnlineUserPool()
        {
            LoginedUserIdentityKey = "FF_OUID";
        }


    }
}
